package cn.xiaobai.captcha.utils;

import cn.xiaobai.captcha.domain.CaptchaBean;
import org.apache.logging.log4j.util.Strings;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author yangdaji
 * @version 1.0
 * @Description: 安全的map进行缓存
 * @date 22-6-12 上午 2:27
 */
public class ConcurrentHashMapCacheUtils {

    /**
     * 缓存map
     */
    private static Map<String, CaptchaBean> concurrentMap = new ConcurrentHashMap<>(16);

    /**
     * 记录缓存失效key
     */
    private static final List<String> CACHE_USE_LOG_LIST = new CopyOnWriteArrayList<>();


    /**
     * 设置缓存
     *
     * @param cacheKey   缓存key
     * @param cacheValue 缓存数据
     */
    public static void setCache(String cacheKey, CaptchaBean cacheValue) {
        concurrentMap.put(cacheKey, cacheValue);
    }

    /**
     * 判断缓存是否过期
     *
     * @param cacheKey 缓存key
     * @return true: 缓存过期
     */
    public static boolean checkCache(String cacheKey) {
        if (Strings.isBlank(cacheKey)) {
            return false;
        }
        if (concurrentMap.isEmpty()) {
            return false;
        }
        if (!concurrentMap.containsKey(cacheKey)) {
            return false;
        }
        CaptchaBean captchaBean = concurrentMap.get(cacheKey);
        //判断缓存时间是否过期
        if (Objects.nonNull(captchaBean) && captchaBean.getCacheTime().getTime() < System.currentTimeMillis()) {
            CACHE_USE_LOG_LIST.add(cacheKey);
            return true;
        }
        return false;
    }

    /**
     * 删除过期key
     */
    public static void deleteTimeOut() {
        CACHE_USE_LOG_LIST.stream().filter(key -> concurrentMap.containsKey(key)).forEach(concurrentMap::remove);
        CACHE_USE_LOG_LIST.clear();
    }

}
